package org.example.seata.common.security.config.resource;

import lombok.AllArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * 资源服务器配置
 *
 * @author hzq
 * @date 2021/12/7 21:27
 */
@Configuration
@AllArgsConstructor
@Import(CustomSecurityInnerAspect.class)
@EnableConfigurationProperties(PermitAllUrl.class)
public class CustomResourceServerConfiguration implements ResourceServerConfigurer {

    private final TokenStore tokenStore;
    private final PermitAllUrl permitAllUrl;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.tokenServices(CustomLocalTokenServices.build(tokenStore))
                .tokenExtractor(CustomBearerTokenExtractor.build(permitAllUrl));
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
        // 注册放行列表
        permitAllUrl.registryAntMatchers(registry);
        registry.anyRequest().authenticated()
                .and()
                .csrf().disable();
    }
}
